import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Modal, message, Input } from 'antd';
import { $http } from 'containers/config/https';
import PublicModalTable from 'pages/common/PublicModalTable';
import Moment from 'moment';
import { Util, dayFormat } from 'tools/index';
const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
};

const CBICDDiagnosDirLinkPopu = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: JSON.parse(window.sessionStorage.userData),
                SelectData: {},
                startDate:Moment(),
                endDate:undefined,
                locID:'',
                dirID:'',
                locList:[],
                visible: false,
                diagnosDirs: [],
                proData: '',
                top: '',
                left: '',
                top1: '',
                left1: '',
                ICDDesc: '',
                ICDObj: {}
            };
            this.modalColumns = [
                {
                    key: 1,
                    title: '代码',
                    dataIndex: 'code',
                    align: "center",
                },
                {
                    key: 2,
                    title: '描述',
                    dataIndex: 'descripts',
                    align: "center",
                },
            ]
            this.myRef1 = React.createRef();
            this.myRef2 = React.createRef();
        }

        componentDidMount() {
            this.props.onRef(this);
            // 初始化数据
            this.loadDiagnosDirs();
            this.getLocSelectData();
        }

        //清空表格内容
        handleReset = () => {
            this.props.form.resetFields();
            this.setState({
                proData: '',
                ICDObj: {}
            })
        };
        // 键盘操作名称模态框数据
        handlePublicModalTableOnKeydown = (e) => {
            var e = window.event || e;
            let scroll_height = 26;
            let id = '';
            let oneArr = this.state.modalData && this.state.modalData.length > 0 ? this.state.modalData : [];
            switch (e.keyCode) {
                case 13:
                    if (this.state.modalRowId) {
                        let obj = {}
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                obj = i > 0 ? oneArr[i] : oneArr[0];
                                break;
                            }
                        }
                        this.confirmSelection(obj);
                    } else {
                        message.info("报错")
                    }
                    break;
                case 38: //上
                    if (this.state.modalRowId) {
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop - scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
                case 40: //下
                    if (this.state.modalRowId) {
                        for (let i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong");
                            gundong.scrollTop = gundong.scrollTop + scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
            }
        };
        // 键盘操作名称模态框数据
        handlePublicModalTableOnKeydown1 = (e) => {
            var e = window.event || e;
            let scroll_height = 26;
            let id = '';
            let oneArr = this.state.modalData1 && this.state.modalData1.length > 0 ? this.state.modalData1 : [];
            switch (e.keyCode) {
                case 13:
                    if (this.state.modalRowId) {
                        let obj = {}
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                obj = i > 0 ? oneArr[i] : oneArr[0];
                                break;
                            }
                        }
                        this.confirmSelection1(obj);
                    } else {
                        message.info("报错")
                    }
                    break;
                case 38: //上
                    if (this.state.modalRowId) {
                        for (var i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i > 0 ? oneArr[i - 1].key : oneArr[0].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong1");
                            gundong.scrollTop = gundong.scrollTop - scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
                case 40: //下
                    if (this.state.modalRowId) {
                        for (let i = 0; i < oneArr.length; i++) {
                            if (oneArr[i].key === this.state.modalRowId) {
                                id = i + 1 >= oneArr.length ? oneArr[oneArr.length - 1].key : oneArr[i + 1].key;
                                break;
                            }
                        }
                        this.setState({ modalRowId: id })
                        setTimeout(() => {
                            var gundong = document.getElementById("gundong1");
                            gundong.scrollTop = gundong.scrollTop + scroll_height;
                        }, 100)
                    } else {
                        this.setState({ modalRowId: oneArr[0].key })
                    }
                    break;
            }
        };
        // 操作弹框
        onClickRowPublic = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelection(record);
                }
            }
        }
        // 操作弹框2
        onClickRowPublic1 = (record) => {
            return {
                onDoubleClick: () => {
                    this.confirmSelection1(record);
                }
            }
        }
        // 双击选中行数据的回调
        confirmSelection = (record) => {
            console.log("record", record)
            this.props.form.setFieldsValue({ code: record.descripts })
            this.setState({ insObj: record }, () => {
                this.child.handleCancel();
            })
        }
        // 双击选中行数据的回调2
        confirmSelection1 = (record) => {
            console.log("record", record)
            this.props.form.setFieldsValue({ linkCode: record.descripts })
            this.setState({ ICDObj: record }, () => {
                this.child1.handleCancel();
            })
        }
        setRowClassNamePublic = (record) => {
            return record.key === this.state.modalRowId ? 'clickRowStyle' : '';
        }
        setRowClassNamePublic1 = (record) => {
            return record.key === this.state.modalRowId ? 'clickRowStyle' : '';
        }
        onRef = (ref) => {
            this.child = ref;
        }
        onRef1 = (ref) => {
            this.child1 = ref;
        }
        // 医保名称回车事件
        // nameOnPressEnter = (e) => {
        //     if (!e.target.value) {
        //         message.info("请输入名称回车搜索")
        //         return;
        //     }
        //     let top = document.getElementById('name-input').getBoundingClientRect().top + 40 + 'px';
        //     let left = document.getElementById('name-input').getBoundingClientRect().left + 'px';
        //     this.setState({
        //         top: top,
        //         left: left,
        //         insDesc: e.target.value
        //     }, () => {
        //         this.getInsuDiagnosisAlias("show");
        //     });
        // }
        // 名称回车事件2
        nameOnPressEnter1 = (e) => {
            if (!e.target.value) {
                message.info("请输入名称回车搜索")
                return;
            }
            let top1 = document.getElementById('name-input1').getBoundingClientRect().top + 40 + 'px';
            let left1 = document.getElementById('name-input1').getBoundingClientRect().left + 'px';
            this.setState({
                top1: top1,
                left1: left1,
                ICDDesc: e.target.value
            }, () => {
                this.getICDAlias("show");
            });
        }
        // 名称失焦操作
        handleOnBlur = (e) => {
            if (this.state.stockID) {
                let arr = this.state.modalData ? JSON.parse(JSON.stringify(this.state.modalData)) : '';
                let status = false;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].stockDesc === e.target.value) {
                        status = true;
                        break;
                    }
                }
                if (!status) {
                    this.setState({ stockID: '', stockDesc: undefined })
                }
            } else {
                this.setState({ stockID: '', stockDesc: undefined })
            }
        }
        // 名称失焦操作2
        handleOnBlur1 = (e) => {
            if (this.state.stockID) {
                let arr = this.state.modalData1 ? JSON.parse(JSON.stringify(this.state.modalData1)) : '';
                let status = false;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].stockDesc === e.target.value) {
                        status = true;
                        break;
                    }
                }
                if (!status) {
                    this.setState({ stockID: '', stockDesc: undefined })
                }
            } else {
                this.setState({ stockID: '', stockDesc: undefined })
            }
        }
        //获取医保诊断别名

        //获取ICD诊断别名
        getICDAlias(isShow) {
            let { ICDDesc } = this.state
            var params = {
                params: [{
                    desc: ICDDesc
                }]
            }
            $http.post('urlDeault', this, {
                code: "05100393",
                data: params,
                success: function (res) {
                    if (res.errorCode == '0') {
                        let arr = res.data ? res.data : [];
                        for (var i = 0; i < arr.length; i++) {
                            arr[i].key = i + 1
                        }
                        this.setState({ modalData1: arr, modalRowId: arr && arr.length > 0 ? arr[0].key : '' }, () => {
                            isShow === 'show' ? this.child1.showModal() : '';
                        })
                    }else {
                        this.setState({ modalData: [], total: 0 });
                        isShow === 'show' ? this.child1.showModal() : '';
                    }
                }
            });
        }

        // 获取科室下拉数据
        getLocSelectData = () => {
            let { userInfo } = this.state;
            var params = {
                params: [{
                    hospID: userInfo && userInfo.hospID ? userInfo.hospID : "",
                }]
            }
            $http.post('urlDeault', this, {
                code: "01050008",
                data: params,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let locList = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
                        this.setState({
                            locList,
                            locID: res.result && res.result.defaultLocID ? String(res.result.defaultLocID) : undefined
                        })
                    }
                }
            });
        }
        // 获取下拉框
        loadDiagnosDirs() {
            var params = {
                params: [{}]
            }
            $http.post('urlDeault', this, {
                code: "01070004",
                data: params,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setState({
                            diagnosDirs: res.result.data,
                        })
                    }
                }
            });
        }
        //保存
        handleSave = () => {
            this.props.form.validateFields((err, val) => {
                let obj = JSON.parse(JSON.stringify(val));
                let { userInfo, proData,ICDObj,locID,startDate,endDate,dirID } = this.state;
                console.log("ICDObj",ICDObj)
                if (err == null) {
                    let data = {
                        params: [{
                            ID: proData && proData.rowId || "",
                            DirectoryDr: dirID || "",
                            ICDID: ICDObj.id? ICDObj.id : '',
                            startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : Moment(new Date()).format('YYYY-MM-DD'),
                            endDate: endDate? Moment(endDate).format('YYYY-MM-DD') : '',
                            locID: locID && locID || '',
                        }],
                    };
                    $http.post('urlS', this, {
                        code: "01070002",
                        data: data,
                        success: function (res) {
                            if (res.errorCode == 0) {
                                message.success(res.errorMessage);
                                this.props.handleThis.getTableData();
                                this.handleReset();
                                this.handleCancel();
                            }
                        }
                    });
                }
            })
        };

        // 开始日期
        handleStartDateChange = e => {
            this.setState({ startDate: e })
        }

        // 开始日期
        handleEndDateChange = e => {
            this.setState({ endDate: e })
        }

        // 关闭
        handleCancel = () => {
            this.props.form.resetFields();
            this.setState({
                visible: false,
            });
        };

        // 打开弹框
        showModal = (obj,ICDObj) => {
            this.setState({
                visible: true,
                proData: obj,
                startDate: (obj && obj.startDate)?new Moment(obj.startDate):new Moment(),
                endDate: (obj && obj.endDate)? new Moment(obj.endDate): '',
                locID:obj && obj.locID || '',
                dirID: obj && obj.directoryID || '',
                ICDObj:ICDObj
            });
        };
        render() {
            let { left, top, modalData,left1, top1, modalData1,ICDObj,startDate,endDate,locID } = this.state;
            const { getFieldDecorator } = this.props.form;
            let { proData } = this.state
            //下拉列表
            let directory = [];
            this.state.diagnosDirs && this.state.diagnosDirs.map((item, i) => {
                directory.push(<Option value={item.id} key={i}>{item.descripts}</Option>)
            });

            // 科室
            let locOption = [];
            this.state.locList && this.state.locList.map((item, index) => {
                locOption.push(<Option key={index} value={String(item.id)} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
            })

            let param = {
                width: '700px',
                height: 300,
                top: top,
                left: left,
                columns: this.modalColumns,
                data: modalData,
                isOnRow: true,
                TableClassName: 'tab-placeholder',
                rowClassName: true,
            }
            let param1 = {
                width: '700px',
                height: 300,
                top: top1,
                left: left1,
                columns: this.modalColumns,
                data: modalData1,
                isOnRow: true,
                TableClassName: 'tab-placeholder',
                rowClassName: true,
            }
            return (
                <Modal
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width='50%'
                    footer={null}
                    className="DiagnosticQueryPopu"
                >
                    <Row style={{ marginTop: '20px' }}>
                        <Card
                            size="small"
                            title="修改/保存关联"
                        >
                            <Col>
                                <Form>
                                    <Row>
                                        <Col span={12}>
                                            <FormItem {...formItemLayout} label='选择科室'>
                                                {getFieldDecorator('locID', {
                                                    initialValue: this.state.locID,
                                                    rules: [{ message: '请选择科室' }],
                                                })(
                                                    <Select showSearch allowClear optionFilterProp="seatchprop" placeholder='请选择开单科室' onChange={Util.handleSelectChange.bind(this, 'locID')}>
                                                        {locOption}
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>

                                    </Row>
                                    <Row>
                                        <Col span={12}>
                                            <div id="name-input" >
                                                <FormItem {...formItemLayout} label={'病种目录'}>
                                                    {getFieldDecorator('directoryId', {
                                                        initialValue: proData && proData.directoryDesc || undefined,
                                                        rules: [{ required: '病种目录不能为空' }]
                                                    })(
                                                        <Select showSearch allowClear placeholder={'请选择病种目录'}  onChange={Util.handleSelectChange.bind(this, 'dirID')} >
                                                            {directory}
                                                        </Select>
                                                    )}
                                                </FormItem>
                                            </div>
                                        </Col>
                                        <Col span={12}>
                                            <div id="name-input1" >
                                                <FormItem {...formItemLayout} label={'关联ICD'}>
                                                    {getFieldDecorator('linkCode', {
                                                        initialValue: ICDObj && ICDObj.descripts || undefined,
                                                        rules: [{ required: '关联ICD不能为空' }]
                                                    })(
                                                        <Input placeholder={'请输入关联ICD'} onPressEnter={this.nameOnPressEnter1}
                                                            onBlur={this.handleOnBlur1}
                                                            autoComplete="off"
                                                            allowClear
                                                            ref={this.myRef2} />
                                                    )}
                                                </FormItem>
                                            </div>
                                            <div
                                                tabIndex={2}
                                                onKeyDown={this.handlePublicModalTableOnKeydown1}
                                                style={{ outline: 'none' }}
                                            >
                                                <PublicModalTable
                                                    onClickRowPublic={this.onClickRowPublic1}
                                                    setRowClassNamePublic={this.setRowClassNamePublic1}
                                                    param={param1}
                                                    onRef={this.onRef1}
                                                    id="gundong1"
                                                />
                                            </div>
                                        </Col>
                                    </Row>
                                   
                                    <Row>
                                        <Col span={12}>
                                        <div id="name-input" >
                                            <FormItem {...formItemLayout} label={'生效日期：'}>
                                            <DatePicker
                                                format="YYYY-MM-DD"
                                                placeholder="请选择生效日期"
                                                value={startDate}
                                                allowClear
                                                onChange={this.handleStartDateChange}
                                            />
                                            </FormItem>
                                        </div>
                                        </Col>

                                        <Col span={12}>
                                        <div id="name-input1" >
                                            <FormItem {...formItemLayout} label={'失效日期：'}>
                                            <DatePicker
                                                format="YYYY-MM-DD"
                                                placeholder="请选择失效日期"
                                                value={endDate}
                                                allowClear
                                                onChange={this.handleEndDateChange}
                                            />
                                            </FormItem>
                                        </div>
                                        </Col>
                                    </Row>
                                    {/* <Row>
                                        <Col span={12}>
                                            <FormItem {...formItemLayout} label={'关联ICD代码'}>
                                                {getFieldDecorator('linkCode', {
                                                    initialValue: proData && proData.ICDCode || undefined,
                                                    rules: [{ required: '关联ICD代码不能为空' }]
                                                })(
                                                    <Input placeholder={'请输入关联ICD代码'} />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={12}>
                                            <FormItem {...formItemLayout} label={'关联ICD描述'}>
                                                {getFieldDecorator('linkDesc', {
                                                    initialValue: proData && proData.ICDDesc || undefined,
                                                    rules: [{ required: '关联ICD描述不能为空' }]
                                                })(
                                                    <Input placeholder={'请输入关联ICD描述'} />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row> */}
                                    <Row style={{ marginTop: '4px', textAlign: 'center' }} className="buttonLeft">
                                        <Button onClick={this.handleSave}>保存</Button>
                                        <Button style={{ marginLeft: '90px' }} onClick={this.handleReset}>清空</Button>
                                    </Row>
                                </Form>
                            </Col>
                        </Card>
                    </Row>
                </Modal>
            )
        }
    }
);
export default CBICDDiagnosDirLinkPopu;